use anyhow::{Result, Context};
use toml;

#[derive(serde::Deserialize)]
pub struct Setting {
    pub database: DatabaseSetting,
    pub application_port: u16
}


#[derive(serde::Deserialize)]
pub struct DatabaseSetting { 
    pub sqlite_path: String,
    pub max_connections: u16 
}

impl Setting{
    pub fn from_toml(path: &str) -> Result<Self> {
        let file = std::fs::read_to_string(path).context("can't read config file")?;
        let setting: Setting = toml::from_str(&file).context("fail to parse toml file")?;
        Ok(setting)
    }
}

impl Default for DatabaseSetting{
    fn default() -> Self {
        Self {
            sqlite_path: "./db/database.sqlite".to_string(),
            max_connections: 10
        }
    }
}

impl Default for Setting {    
    fn default() -> Self {
        Self {
            database: DatabaseSetting::default(),
            application_port: 3001
        }
    }
}